package com.hsnn.medstgmini.base.std.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.StdDrugQualitySpec;
import com.hsnn.medstgmini.base.std.model.StdDrugQualitySpecLog;
import com.hsnn.medstgmini.base.std.service.StdDrugQualitySpecManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.AccountUtil;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.PinYin;

/**
 * @category 品规库
 * @author CCL
 */
@Controller
@RequestMapping("stdDrugQualitySpec")
public class StdDrugQualitySpecController {

	private static final Logger log = Logger.getLogger(StdDrugQualitySpecController.class);
	@Autowired
	private StdDrugQualitySpecManager stdDrugQualitySpecManager;
	
	@Autowired
	private HttpServletRequest request;
	
	/**
	 *@category 跳转到品规列表页面
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return String
	 */
	@RequestMapping("toDrugQualitySpecList")
	public String toDrugQualitySpecList(){
		return "/base/std/drugQualitySpecList";
	}
	
	/**
	 *@category 跳转到维护记录列表页面
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return String
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("toDrugQualitySpecLogList")
	public String toDrugQualitySpecLogList(Model model) throws UnsupportedEncodingException{
		printParams();
		String qualitySpecId = request.getParameter("qualitySpecId");
		model.addAttribute("qualitySpecId", qualitySpecId);
		String qualitySpecName = new String(request.getParameter("qualitySpecName").getBytes("ISO8859-1"),"utf-8");
		model.addAttribute("qualitySpecName",qualitySpecName);
		String qualitySpecCode = request.getParameter("qualitySpecCode");
		model.addAttribute("qualitySpecCode",qualitySpecCode);
		return "/base/std/drugQualitySpecLogList";
	}
	
	
	/**
	 *@category 跳转到品规详情页面
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return String
	 */
	@RequestMapping("toDrugQualitySpecDetail")
	public String toDrugQualitySpecDetail(Model model){
		printParams();
		String drugQualitySpecId = request.getParameter("drugQualitySpecId");
		String opType = request.getParameter("opType");
		if(null !=drugQualitySpecId){
			StdDrugQualitySpec stdDrugQualitySpec = stdDrugQualitySpecManager.getDrugQualitySpecById(drugQualitySpecId);
			model.addAttribute("stdDrugQualitySpec", stdDrugQualitySpec);
			model.addAttribute("opType", opType);
		}
		return "/base/std/drugQualitySpecDetail";
	}
	
	/**
	 *@category 跳转到编辑页面
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return String
	 */
	@RequestMapping("toDrugQualitySpecEdit")
	public String toDrugQualitySpecEdit(Model model){
		printParams();
		String drugQualitySpecId = request.getParameter("drugQualitySpecId");
		String opType = request.getParameter("opType");
		if(null !=drugQualitySpecId){
			StdDrugQualitySpec stdDrugQualitySpec = stdDrugQualitySpecManager.getDrugQualitySpecById(drugQualitySpecId);
			model.addAttribute("stdDrugQualitySpec", stdDrugQualitySpec);
		}
		model.addAttribute("opType", opType);
		return "/base/std/drugQualitySpecEdit";
	}
	
	/**
	 *@category 跳转到详情页面
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return String
	 */
	@RequestMapping("toDrugQualitySpecDetial")
	public String toDrugQualitySpectDetial(Model model){
		printParams();
		String drugQualitySpecId = request.getParameter("drugQualitySpecId");
		StdDrugQualitySpec stdDrugQualitySpec = stdDrugQualitySpecManager.getDrugQualitySpecById(drugQualitySpecId);
		model.addAttribute("stdDrugQualitySpec", stdDrugQualitySpec);
		return "/base/std/drugQualitySpectDetial";
	}
	
	/**
	 *@category 查询维护记录列表
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return Pagination
	 */
	@RequestMapping("getDrugQualitySpecLogList")
	@ResponseBody
	public Pagination getDrugQualitySpecLogList(StdDrugQualitySpec stdDrugQualitySpec){
		printParams();
		Pagination page = new Pagination(request);
		String startPoint = (String)request.getParameter("startPoint");
		String endPoint = (String)request.getParameter("endPoint");
		String qualitySpecId = request.getParameter("qualitySpecId");
		String updDatetime = request.getParameter("updDatetime");
		if(StringUtils.isNoneBlank(startPoint)){
			page.getConditions().put("startPoint", startPoint);
		}
		if(StringUtils.isNoneBlank(endPoint)){
			page.getConditions().put("endPoint", endPoint);
		}
		if(StringUtils.isNoneBlank(qualitySpecId)){
			page.getConditions().put("qualitySpecId", qualitySpecId);
		}
		if(StringUtils.isNoneBlank(updDatetime)){
			page.getConditions().put("updDatetime", updDatetime);
		}
		try {
			page = stdDrugQualitySpecManager.getStdDrugQualitySpecLogList(page,stdDrugQualitySpec);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 *@category 查询品规列表
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return Pagination
	 */
	@RequestMapping("getDrugQualitySpecList")
	@ResponseBody
	public Pagination getDrugQualitySpecList(){
		printParams();
		Pagination page = new Pagination(request);
		String drugQualitySpecName = request.getParameter("drugQualitySpecName");
		String drugQualitySpecCode = request.getParameter("drugQualitySpecCode");
		String formName = request.getParameter("formName");
		String specName = request.getParameter("specName");
		String status = request.getParameter("status");
		if(StringUtils.isNoneBlank(drugQualitySpecName)){
			page.getConditions().put("drugQualitySpecName", drugQualitySpecName);
		}
		if(StringUtils.isNoneBlank(drugQualitySpecCode)){
			page.getConditions().put("drugQualitySpecCode", drugQualitySpecCode);
		}
		if(StringUtils.isNoneBlank(formName)){
			page.getConditions().put("formName", formName);
		}
		if(StringUtils.isNoneBlank(specName)){
			page.getConditions().put("specName", specName);
		}
		if(StringUtils.isNoneBlank(status)){
			page.getConditions().put("status", status);
		}
		try {
			page = stdDrugQualitySpecManager.getStdDrugQualitySpecList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 *@category 新增或编辑品规
	 *@author 周奇
	 *@date 2015年8月18日11:23:40
	 *@return 
	 */
	@RequestMapping(value={"/add","/edit"})
	@ResponseBody
	public Pagination saveOrEditDrugQualitySpec(StdDrugQualitySpec stdDrugQualitySpec){
		printParams();
		Pagination page = new Pagination();
		try{
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			stdDrugQualitySpec.setUpdDatetime(DateUtil.getTimeStamp());//设置更新时间
			stdDrugQualitySpec.setUpdUser(user.getId());//设置更新人
			String qualityspecId = stdDrugQualitySpec.getQualitySpecId();
        	String qualityspecCode = stdDrugQualitySpec.getQualitySpecCode();
        	String qualityspecName = stdDrugQualitySpec.getQualitySpecName();
        	String qualityspecNameEng = stdDrugQualitySpec.getQualitySpecNameEng();
        	String form = stdDrugQualitySpec.getForm();
        	String formName = stdDrugQualitySpec.getFormName();
        	String spec = stdDrugQualitySpec.getSpec();
        	String specName = stdDrugQualitySpec.getSpecName();
			if(StringUtils.isNotBlank(stdDrugQualitySpec.getQualitySpecId())){//编辑情况
				String stdQualitySpecId = stdDrugQualitySpec.getQualitySpecId();
				StdDrugQualitySpec drugQualitySpec = stdDrugQualitySpecManager.getDrugQualitySpecById(stdQualitySpecId);
				if(null ==drugQualitySpec){
					page.setSuccess(false);
					page.setMsg("保存失败");
					return page;
				}
				stdDrugQualitySpec.setStatus(drugQualitySpec.getStatus());
				
			}
			if(StringUtils.isBlank(stdDrugQualitySpec.getQualitySpecId())){//新增情况
				stdDrugQualitySpec.setQualitySpecId(UUID.randomUUID().toString());//设置UUID
				stdDrugQualitySpec.setStatus(1);
				stdDrugQualitySpec.setQualitySpecCode(AccountUtil.getStdSequence(Constants.STD_PINGGUI_PREFIX, Constants.STD_PINGGUI, Constants.STD_PINGGUI_LEN));
				page.setMsg(stdDrugQualitySpec.getQualitySpecCode());
			}
			stdDrugQualitySpec.setQualitySpecNameSpel(PinYin.getPinYin(stdDrugQualitySpec.getQualitySpecName()));
			List<StdDrugQualitySpec>  list = stdDrugQualitySpecManager.validRep(stdDrugQualitySpec);
			 	page.getConditions().put("qualityspecId", qualityspecId);
	            page.getConditions().put("qualityspecName", qualityspecName);
	            page.getConditions().put("qualityspecCode", qualityspecCode);
	            page.getConditions().put("qualityspecNameEng", qualityspecNameEng);
	            page.getConditions().put("form", form);
	            page.getConditions().put("formName", formName);
	            page.getConditions().put("spec", spec);
	            page.getConditions().put("specName", specName);
				page.getConditions().put("updUser", user.getId());
				
			stdDrugQualitySpecManager.saveOrAddDrugQualitySpec(page);
			page.setSuccess(true);
			page.setMsg(stdDrugQualitySpec.getQualitySpecCode());
			/*if(list.size()> 0){
				page.setSuccess(false);
				page.setMsg("品规编码已存在！请重新填写");
				return page;
			}*/
		}catch(Exception e){
			log.error("",e);
			page.setSuccess(false);
			page.setMsg("保存失败！");
		}
		return page;
	}
	
	
	/**
	 *@category 改变状态
	 *@author 徐国鹏
	 *@date 2015年8月18日11:23:40
	 *@return Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatuss(String array){
		printParams();
		Pagination page = new Pagination();
		int count = 0;
		try{
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<StdDrugQualitySpec>>() {}.getType();
				List<StdDrugQualitySpec> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (StdDrugQualitySpec ddt : list) {
						ddt.setUpdUser(user.getId());
						count = stdDrugQualitySpecManager.saveOrAddDrugSpec(ddt);
					}
					page.setSuccess(true);
					page.getConditions().put("count", count+"");
				}else{
					page.setSuccess(false);
				}
			}
		} catch(Exception e){
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * @category 获取编辑数据
	 * @author zhouqi
	 * @date 2015年8月21日14:39:08
	 * @param void
	 * @return Pagination
	 */
	@RequestMapping("getStdDrugQualitySpecForEdit")
	@ResponseBody
	Pagination getStdDrugQualitySpecForEdit(String drugQualitySpecId){
		printParams();
		Pagination page = new Pagination();
		StdDrugQualitySpec stdDrugQualitySpec = new StdDrugQualitySpec();
		try{
			if(StringUtils.isNotBlank(drugQualitySpecId)){
				stdDrugQualitySpec = stdDrugQualitySpecManager.getDrugQualitySpecById(drugQualitySpecId);
				page.setRows(stdDrugQualitySpec);
				page.setSuccess(true);
			}else{
				page.setSuccess(false);
			}	
		}catch(Exception e){
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * 品规库维护记录详情
	 * @param page
	 * @return
	 */
	@RequestMapping("/toStdDrugQualitySpecLogDetail")
	public String  toStdDrugQualitySpecLogDetail(Model model, StdDrugQualitySpecLog stdDrugQualitySpecLog) {
		printParams();
		List<Map<String,Object>> list = stdDrugQualitySpecManager.getStdDrugQualitySpecLogDetail(stdDrugQualitySpecLog);
		
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		String[] cColunm = {"品规编码","品规名称","品规英文名","剂型名称","规格名称","状态"};
		String[] eColunm = {"qualitySpecCode","qualitySpecName","qualitySpecNameEng","formName","specName","status"};
		for(int i = 0;i<cColunm.length;i++){
			Map<String,Object> map =  new HashMap<String,Object>();
			map.put("colunm", cColunm[i]);//字段名
			map.put("after", !"status".equals(eColunm[i])?list.get(0).get(eColunm[i]):"1".equals(list.get(0).get(eColunm[i]).toString())?"启用":"停用");//修改后数据
			map.put("before", list.size()==1?null:!"status".equals(eColunm[i])?list.get(1).get(eColunm[i]):"1".equals(list.get(1).get(eColunm[i]).toString())?"启用":"停用");//修改前数据
			if(list.size()==1){
				map.put("red", "1");//是否变红加粗 1是 0 否
			}else{
				//判断修改后与修改前数据是否相等
				if(list.get(0).get(eColunm[i])!=null&&list.get(1).get(eColunm[i])!=null&&!list.get(0).get(eColunm[i]).toString().equals(list.get(1).get(eColunm[i]).toString())){
					map.put("red", "1");
				}else{
					map.put("red", "0");
				}
			}
			mapList.add(map);
		}
		for(int i = 0;i<mapList.size();i++){//把要变红的放在list前面
			if("1".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		for(int i = 0;i<mapList.size();i++){
			if("0".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		request.setAttribute("dataList", dataList);
		request.setAttribute("list", list);
		return "/base/std/drugQualitySpecLogDetail";
	}
	
	
	
	/**
	 * 
	 * @category 品规库 新增编辑  剂型 弹窗
	 * @author 言科
	 * @date 2015年9月25日 String
	 */
	@RequestMapping("/toStdDrugQualitySpecDrugForm")
	public String  toStdDrugQualitySpecDrugForm() {
		log.info("enter toStdDrugQualitySpecDrugForm method!");
		return "/base/std/stdDrugQualitySpecDrugForm";
	}
	//获取剂型列表数据
	@RequestMapping("/getStdDrugQualitySpecDrugForm")
	@ResponseBody
	public Pagination getStdDrugQualitySpecDrugForm(){
		printParams();
		log.info("enter getStdDrugQualitySpecDrugForm method!");
		Pagination page =new Pagination(request);
		String formCode = request.getParameter("formCode");
		String formName = request.getParameter("formName");
		if(StringUtils.isNotBlank(formCode)){
			page.getConditions().put("formCode", formCode.trim());
		}
		if(StringUtils.isNotBlank(formName)){
			page.getConditions().put("formName", formName.trim());
		}
		try{
		page = stdDrugQualitySpecManager.getStdDrugQualitySpecDrugForm(page);
		page.setSuccess(true);
		}catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	
	
	/**
	 * 
	 * @category 品规库 新增编辑  规格 弹窗
	 * @author 言科
	 * @date 2015年9月25日 String
	 */
	@RequestMapping("/toStdDrugQualitySpecDrugSpec")
	public String  toStdDrugQualitySpecDrugSpec() {
		log.info("enter toStdDrugQualitySpecDrugSpec method!");
		return "/base/std/stdDrugQualitySpecDrugSpec";
	}
	//获取剂型列表数据
	@RequestMapping("/getStdDrugQualitySpecDrugSpec")
	@ResponseBody
	public Pagination getStdDrugQualitySpecDrugSpec(){
		printParams();
		log.info("enter getStdDrugQualitySpecDrugSpec method!");
		Pagination page =new Pagination(request);
		String specCode = request.getParameter("specCode");
		String specName = request.getParameter("specName");
		if(StringUtils.isNotBlank(specCode)){
			page.getConditions().put("specCode", specCode.trim());
		}
		if(StringUtils.isNotBlank(specName)){
			page.getConditions().put("specName", specName.trim());
		}
		try{
		page = stdDrugQualitySpecManager.getStdDrugQualitySpecDrugSpec(page);
		page.setSuccess(true);
		}catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author 徐国鹏
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String qualityspecCode = request.getParameter("qualityspecCode");
		String qualityspecName = request.getParameter("qualityspecName");
		String formName = request.getParameter("formName");
		String specName = request.getParameter("specName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(qualityspecCode)){
			page.getConditions().put("qualityspecCode", qualityspecCode.trim());
		}
		if(StringUtils.isNotBlank(qualityspecName)){
			page.getConditions().put("qualityspecName", qualityspecName.trim());
		}
		if(StringUtils.isNotBlank(formName)){
			page.getConditions().put("formName", formName.trim());
		}
		if(StringUtils.isNotBlank(specName)){
			page.getConditions().put("specName", specName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String("品规.xls".getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			 stdDrugQualitySpecManager.exportExcel(page,os);

		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}



